#include <stdio.h>
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"

#define GAME_WIDTH  800
#define GAME_HEIGHT 600

typedef struct _GAME_DATA{
    SDL_Window *pWindow;
    SDL_Renderer *pRender;

    SDL_Texture *pJet;
    SDL_Rect rcJet;
} GAME_DATA_T;

static GAME_DATA_T s_data;

int init();
void deinit();

void loadJet();
void unloadJet();

int main(int argc, char *argv[])
{
    int nRet = init();
    if(nRet != 0) return nRet;

    loadJet();
    const uint8_t *pKeyState = SDL_GetKeyboardState(NULL);

    int speedX, speedY;

    // the main event loop
    int bQuit = 0;
    while(!bQuit){
        SDL_Event ev;

        while(SDL_PollEvent(&ev)){
            if(ev.type == SDL_QUIT) bQuit = 1;
        }

        speedX = 0;
        speedY = 0;
        if(pKeyState[SDL_SCANCODE_LEFT]) speedX -= 5;
        if(pKeyState[SDL_SCANCODE_RIGHT]) speedX += 5;
        if(pKeyState[SDL_SCANCODE_UP]) speedY -= 5;
        if(pKeyState[SDL_SCANCODE_DOWN]) speedY += 5;

        s_data.rcJet.x += speedX;
        s_data.rcJet.y += speedY;

        SDL_SetRenderDrawColor(s_data.pRender, 0x00, 0x00, 0x30, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(s_data.pRender);

        SDL_RenderCopy(s_data.pRender, s_data.pJet, NULL, &s_data.rcJet);
        

        SDL_RenderPresent(s_data.pRender);
    }

    unloadJet();
    deinit();

    return 0;
}

int init()
{
    int nRet;
    // 初始化SDL2
    nRet = SDL_Init(SDL_INIT_EVERYTHING);
    if(nRet != 0) return nRet;

    s_data.pWindow = SDL_CreateWindow("GAME01",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        GAME_WIDTH, GAME_HEIGHT,
        SDL_WINDOW_SHOWN);
    
    s_data.pRender = SDL_CreateRenderer(s_data.pWindow, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);

    return 0;
}

void deinit()
{
    SDL_DestroyRenderer(s_data.pRender);
    s_data.pRender = NULL;

    SDL_DestroyWindow(s_data.pWindow);
    s_data.pWindow = NULL;
}

void loadJet()
{
    SDL_Surface *pImgSurface = IMG_Load("../images/jet_small.png");
    s_data.pJet = SDL_CreateTextureFromSurface(s_data.pRender, pImgSurface);
    s_data.rcJet.w = pImgSurface->w;
    s_data.rcJet.h = pImgSurface->h;
    SDL_FreeSurface(pImgSurface);
}

void unloadJet()
{
    SDL_DestroyTexture(s_data.pJet);
    s_data.pJet = NULL;
}